// src/features/members/components/profile.tsx
import React, {useEffect, useState} from 'react';
import {useGetMember} from "@/features/members/api/use-get-member";
import {Member, Role} from "@/lib/social/types";
import {AlertTriangle, ChevronDownIcon, Loader, MailIcon, XIcon} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Avatar, AvatarFallback, AvatarImage} from "@/components/ui/avatar";
import {Separator} from "@/components/ui/separator";
import Link from "next/link";
import {useUpdateMember} from "@/features/members/api/use-update-member";
import {useRemoveMember} from "@/features/members/api/use-remove-member";
import {useCurrentMember} from "@/features/workspaces/api/use-current-member";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {toast} from "sonner";
import UseConfirm from "@/hooks/social/use-confirm";
import {useRouter} from "next/navigation";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuRadioGroup, DropdownMenuRadioItem,
    DropdownMenuTrigger
} from "@/components/ui/dropdown-menu";
import {useCurrentUser} from "@/hooks/use-current-user";

interface Props {
    memberId: string
    onClose: () => void
}

const Profile = ({memberId, onClose}: Props) => {
    const router = useRouter()
    const user = useCurrentUser()

    const workspaceId = useWorkspaceId()

    const [RemoveDialog, confirmRemove] = UseConfirm(
        `Remove member`,
        `Are you sure you want to remove this member?`
    )
    const [LeaveDialog, confirmLeave] = UseConfirm(
        `Leave workspace`,
        `Are you sure you want to leave this workspace?`
    )
    const [UpdateDialog, confirmUpdate] = UseConfirm(
        `Change role`,
        `Are you sure you want to change this member's role?`
    )

    const [member, setMember] = useState<Member>();
    const [curMember, setCurMember] = useState<Member>();
    const [loading, setLoading] = useState(false);

    const {mutate: updateMember, isPending: isUpdatingMember} = useUpdateMember()
    const {mutate: removeMember, isPending: isRemovingMember} = useRemoveMember()

    useEffect(() => {
        (async () => {
            const {data, isLoading} = await useGetMember({id: memberId})
            setLoading(isLoading)
            setMember(data)

            const {data: curM, isLoading: isMLoading} = await useCurrentMember(
                {workspaceId, userId: user?.id!}
            )
            setLoading(prev => prev || isMLoading)
            setCurMember(curM)

            console.log('profile', data, curM)
        })()
    }, [memberId])

    const onRemove = async () => {
        const ok = await confirmRemove()
        if (!ok) return

        await removeMember({id: memberId}, {
            onSuccess() {
                toast.success("You left the workspace")
                onClose()
            },
            onError() {
                toast.error(`Failed to leave the workspace`)
            }
        })
    }

    const onLeave = async () => {
        const ok = await confirmLeave()
        if (!ok) return

        await removeMember({id: memberId}, {
            onSuccess() {
                router.replace('/')
                toast.success("Member removed")
                onClose()
            },
            onError() {
                toast.error(`Failed to remove member`)
            }
        })
    }

    const onUpdate = async (role: Role) => {
        const ok = await confirmUpdate()
        if (!ok) return

        await updateMember({id: memberId, role}, {
            onSuccess() {
                toast.success("Role changed")
                onClose()
            },
            onError() {
                toast.error(`Failed to change role`)
            }
        })
    }

    if (loading) return <div
        className={`flex h-full items-center justify-center`}>
        <Loader className={`size-5 animate-spin text-muted-foreground`}/>
    </div>

    if (!member)
        return <div className={`h-full flex flex-col`}>
            <div className={`h-[49px] flex justify-between items-center px-4 border-b`}>
                <p className={`text-lg font-bold`}>Profile</p>
                <Button onClick={onClose} size={'iconSm'} variant={'ghost'}>
                    <XIcon className={`size-5 stroke-[1.5]`}/>
                </Button>
            </div>
            <div className={`flex flex-col gap-y-2 h-full items-center justify-center`}>
                <AlertTriangle className={`size-5 text-muted-foreground`}/>
                <p className={`text-sm text-muted-foreground`}>Profile not found</p>
            </div>
        </div>

    return (
        <>
            <RemoveDialog/>
            <LeaveDialog/>
            <UpdateDialog/>
            <div className={`h-full flex flex-col`}>
                <div className={`h-[49px] flex justify-between items-center px-4 border-b`}>
                    <p className={`text-lg font-bold`}>Profile</p>
                    <Button onClick={onClose} size={'iconSm'} variant={'ghost'}>
                        <XIcon className={`size-5 stroke-[1.5]`}/>
                    </Button>
                </div>
                <div className={`flex flex-col items-center justify-center p-4`}>
                    <Avatar className={`max-w-[256px] max-h-[256px] size-full rounded-md`}>
                        <AvatarImage
                            className={`rounded-md`}
                            // @ts-ignore
                            src={member.user.image}
                        />
                        <AvatarFallback className={`aspect-square bg-blue-400 text-6xl text-white rounded-md`}>
                            {/*@ts-ignore*/}
                            {member.user.name.charAt(0).toUpperCase()}
                            {/*{'A'.charAt(0).toUpperCase()}*/}
                        </AvatarFallback>
                    </Avatar>
                </div>
                <div className={`flex flex-col p-4`}>
                    <p className={`text-xl font-bold`}>
                        {/*@ts-ignore*/}
                        {member.user.name}
                        {/*Malred*/}
                    </p>
                    {curMember?.role === 'admin' && // todo 被踢不能是管理
                    curMember?.id !== memberId ? ( // 如果看的是别人的消息面板 & 是管理员
                        <div className={`flex items-center gap-2 mt-4`}>
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button className={`w-full capitalize`} variant={'outline'}>
                                        {member?.role} <ChevronDownIcon className={`size-4 ml-2`}/>
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent className={`w-full`}>
                                    <DropdownMenuRadioGroup
                                        className={``}
                                        value={member.role}
                                        // @ts-ignore
                                        onValueChange={(role: Role) => onUpdate(role)}
                                    >
                                        <DropdownMenuRadioItem value={Role.ADMIN}>
                                            Admin
                                        </DropdownMenuRadioItem>
                                        <DropdownMenuRadioItem value={Role.MEMBER}>
                                            Member
                                        </DropdownMenuRadioItem>
                                    </DropdownMenuRadioGroup>
                                </DropdownMenuContent>
                            </DropdownMenu>
                            <Button
                                onClick={onRemove}
                                variant={'outline'} className={`w-full`}>
                                Remove
                            </Button>
                        </div>
                    ) : curMember?.id === memberId ? // 管理员和用户应该都能退出? 始终保留一个管理员在频道 todo ai-chat管理员
                        // &&  curMember.role !== 'admin' ? // 用户可以退出, 管理员不行
                        (// 如果看的是自己的消息面板
                            <div className={`mt-4`}>
                                {/*退出*/}
                                <Button
                                    onClick={onLeave}
                                    variant={'outline'} className={`w-full`}>
                                    Leave
                                </Button>
                            </div>
                        ) : null
                    }
                </div>
                <Separator/>
                <div className={`flex flex-col p-4`}>
                    <p className={`text-sm font-bold mb-4`}>
                        Contact information
                    </p>
                    <div className={`flex items-center gap-2`}>
                        <div className={`size-9 rounded-md flex items-center justify-center`}>
                            <MailIcon className={`size-4`}/>
                        </div>
                        <div className={`flex flex-col`}>
                            <p className={`text-[13px] font-semibold text-muted-foreground`}>
                                Email Address
                            </p>
                            <Link href={
                                // @ts-ignore
                                `mailto:${member.user.email}`
                                // 'mailto:malguy2022@gmail.com'
                            }
                                  className={`text-sm hover:underline text-[#1264a3]`}
                            >
                                {/*@ts-ignore*/}
                                {member.user.email}
                                {/*malguy2022@gmail.com*/}
                            </Link>
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};

export default Profile;